package servlet;

import dao.FlowerDao;
import dao.FlowerDaoImpl;
import service.FlowerService;
import service.FlowerServiceImpl;
import entity.Flower;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/flowers")
public class FlowerServlet extends HttpServlet {
    //Mysql语句
//    EATE DATABASE IF NOT EXISTS flowerDB;
//    USE flowerDB;
//    CREATE TABLE IF NOT EXISTS flower (
//            id INT AUTO_INCREMENT PRIMARY KEY,
//            name NVARCHAR(30) NOT NULL,
//    anothername NVARCHAR(30) NOT NULL,
//    property NVARCHAR(20) NOT NULL,
//    price FLOAT NOT NULL,
//    production NVARCHAR(30) NOT NULL
//);
//    INSERT INTO flower (name, anothername, property, price, production)
//    VALUES
//            ('矮牵牛', '碧冬茄', '茄科', 2.5, '南美阿根廷'),
//    ('白晶菊', '晶晶菊', '菊科', 3, '北非'),
//            ('百日草', '步步高', '菊科', 5, '墨西哥');
//
//    SELECT * FROM flower;


    private final FlowerService flowerService;

    public FlowerServlet() {
        FlowerDao flowerDao = new FlowerDaoImpl();
        flowerService = new FlowerServiceImpl(flowerDao);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Flower> flowers = flowerService.getAllFlowers();
        request.setAttribute("flowers", flowers);
        request.getRequestDispatcher("flowers.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        String name = request.getParameter("name");
        String anothername = request.getParameter("anothername");
        String property = request.getParameter("property");
        float price = Float.parseFloat(request.getParameter("price"));
        String production = request.getParameter("production");

        Flower flower = new Flower(name, anothername, property, price, production);
        boolean success = flowerService.addFlower(flower);

        if (success) {
            response.sendRedirect(request.getContextPath() + "/flowers");
        } else {
            request.setAttribute("error", "添加失败，请检查输入");
            request.getRequestDispatcher("addFlower.jsp").forward(request, response);
        }
    }
}
